package singsong;

import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.LinkedList;

import javax.swing.ImageIcon;
import javax.swing.JLabel;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.xy.DefaultXYDataset;


public class BarGraphFactory {
	public static class BarGraphProperties {
		public boolean showFreq = true;
		public boolean showVolume = false;
		public int width = 600;
		public int height = 400;
	}
	
	public static JLabel create(TrackData data, BarGraphProperties props) {
		ArrayList<Double> freqs = new ArrayList<Double>();
		ArrayList<Double> vols = new ArrayList<Double>();
		for (TrackData.Sample sample : data.getSamples()) {
			freqs.add((double)sample.getFrequency());
			vols.add((double)sample.getVolume()*1000);
		}
		
		DefaultXYDataset xy = new DefaultXYDataset();
		float samsPerSecond = 1 / data.getSampleDuration();
		if (props.showFreq)
			addSeries(xy, freqs, 1 / samsPerSecond);
		if (props.showVolume)
			addSeries(xy, vols, 1 / samsPerSecond);
		
		JFreeChart chart = ChartFactory.createXYAreaChart
	        ("Melody",  // Title
	         "time",           // X-Axis label
	         "freq",           // Y-Axis label
	         xy,          // Dataset
	         PlotOrientation.VERTICAL,
	         true,                // Show legend,
	         false,
	         false
	        );
		
		BufferedImage image = chart.createBufferedImage(props.width,props.height);
	    JLabel lblChart = new JLabel();
	    lblChart.setIcon(new ImageIcon(image));
		return lblChart;
	}
			
	private static void addSeries(DefaultXYDataset xy, ArrayList<Double> list, float width) {
		double[][] dubs = new double[2][list.size() * 2];
		float x = 0f;
		for (int i = 0; i < list.size(); i++) {
			dubs[0][i*2] = x;
			x += width;
			dubs[0][i*2+1] = x;
			dubs[1][i*2] = dubs[1][i*2+1] = list.get(i);
		}
		xy.addSeries(new Double(number++), dubs);
	}
	
	private static int number = 0;
		
/* 		DefaultCategoryDataset data = new DefaultCategoryDataset();
		Double garbage = new Double(1);
		float time = 0;
		
		for (int i = 0; i < samples.size(); i+=1) {
			//data.addValue(samples.get(i).frequency, new Double(time), new Double(time));
			time += 1 / samsPerSec;
			//data.addValue(samples.get(i).frequency, garbage, new Double(time - .001));
		}
		data.addValue(1, garbage, new Double(1));
		data.addValue(2, garbage, new Double(2));
		data.addValue(1, garbage, new Double(3));
		*/
}
